<template>
  <div class="expense-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="项目ID">
          <el-input v-model="searchForm.itemId" placeholder="请输入项目ID" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="待审核" :value="1" />
            <el-option label="已审核" :value="2" />
            <el-option label="已拒绝" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计信息 -->
    <el-card class="stats-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-value">{{ totalExpense }}</div>
            <div class="stat-label">总支出</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-value">{{ monthlyExpense }}</div>
            <div class="stat-label">本月支出</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-value">{{ pendingCount }}</div>
            <div class="stat-label">待审核</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-value">{{ approvedCount }}</div>
            <div class="stat-label">已审核</div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 操作按钮 -->
    <el-card class="action-card">
      <el-button type="primary" @click="handleAdd">新增支出单</el-button>
      <el-button type="success" @click="handleBatchApprove">批量审核</el-button>
      <el-button type="warning" @click="handleExport">导出Excel</el-button>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        :data="Array.isArray(tableData) ? tableData : []"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="billNo" label="单据编号" width="150" />
        <el-table-column prop="itemId" label="项目ID" width="120" />
        <el-table-column prop="amount" label="金额" width="120">
          <template #default="{ row }">
            <span class="amount">¥{{ row.amount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="billDate" label="单据日期" width="120">
          <template #default="{ row }">
            {{ formatDate(row.billDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleView(row)">查看</el-button>
            <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button 
              v-if="row.status === 1" 
              size="small" 
              type="success" 
              @click="handleApprove(row)"
            >
              审核
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-if="dialogVisible"
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增支出单' : dialogType === 'edit' ? '编辑支出单' : '查看支出单'"
      width="600px"
      :destroy-on-close="true"
      :append-to-body="true"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        :disabled="dialogType === 'view'"
      >
        <el-form-item label="单据编号" prop="billNo">
          <el-input v-model="form.billNo" placeholder="请输入单据编号">
            <template #append>
              <el-button @click="generateBillNo" :disabled="dialogType === 'view'">自动生成</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="项目ID" prop="itemId">
          <el-input v-model="form.itemId" placeholder="请输入项目ID" />
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input-number v-model="form.amount" :precision="2" :min="0" style="width: 100%" />
        </el-form-item>
        <el-form-item label="单据日期" prop="billDate">
          <el-date-picker
            v-model="form.billDate"
            type="date"
            placeholder="选择日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button v-if="dialogType !== 'view'" type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getExpenseBillList, getExpenseBillStats, addExpenseBill, updateExpenseBill, deleteExpenseBill, approveExpenseBill, batchApproveExpenseBill, exportExpenseBill } from '@/api/finance/expense'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref('add') // add, edit, view
const selectedRows = ref([])
const formRef = ref(null)

// 搜索表单
const searchForm = reactive({
  itemId: '',
  status: '',
  dateRange: []
})

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 表格数据
const tableData = ref([])

// 表单数据
const form = reactive({
  id: null,
  billNo: '',
  itemId: '',
  amount: 0,
  billDate: '',
  status: 1,
  remark: ''
})

// 表单验证规则
const rules = {
  itemId: [{ required: true, message: '请输入项目ID', trigger: 'blur' }],
  amount: [{ required: true, message: '请输入金额', trigger: 'blur' }],
  billDate: [{ required: true, message: '请选择单据日期', trigger: 'change' }]
}

// 统计信息
const totalExpense = ref(0)
const monthlyExpense = ref(0)
const pendingCount = ref(0)
const approvedCount = ref(0)
const totalCount = ref(0)

// 方法
const handleSearch = () => {
  pagination.current = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    itemId: '',
    status: '',
    dateRange: []
  })
  handleSearch()
}

const handleAdd = async () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
  // 自动生成单据编号
  await generateBillNo()
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(form, row)
  dialogVisible.value = true
}

const handleView = (row) => {
  dialogType.value = 'view'
  Object.assign(form, row)
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteExpenseBill(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleApprove = async (row) => {
  try {
    await ElMessageBox.confirm('确定要审核这条记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await approveExpenseBill(row.id)
    ElMessage.success('审核成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('审核失败:', error)
      ElMessage.error('审核失败')
    }
  }
}

const handleBatchApprove = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要审核的记录')
    return
  }
  try {
    await ElMessageBox.confirm(`确定要审核选中的 ${selectedRows.value.length} 条记录吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const ids = selectedRows.value.map(row => row.id)
    await batchApproveExpenseBill(ids)
    ElMessage.success('批量审核成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量审核失败:', error)
      ElMessage.error('批量审核失败')
    }
  }
}

const handleExport = async () => {
  try {
    // 检查是否有数据可以导出
    if (!tableData.value || tableData.value.length === 0) {
      ElMessage.warning('暂无数据可导出，请先加载数据')
      return
    }
    
    ElMessage.info('正在导出支出管理数据，请稍候...')
    
    // 准备CSV数据
    const headers = ['单据编号', '支出项目', '金额', '单据日期', '状态', '备注']
    const dataList = []
    
    // 添加数据行
    tableData.value.forEach(row => {
      dataList.push([
        row.billNo || '',
        row.itemId || '',
        row.amount || 0,
        row.billDate || '',
        getStatusText(row.status),
        row.remark || ''
      ])
    })
    
    // 添加汇总行
    dataList.push([
      '总计',
      '',
      totalExpense.value || 0,
      '',
      `记录数: ${pagination.total || 0}`,
      ''
    ])
    
    // 创建CSV文件并下载
    const workbook = new Blob([
      '\uFEFF' + // BOM for UTF-8
      headers.join(',') + '\n' +
      dataList.map(row => row.join(',')).join('\n')
    ], { type: 'text/csv;charset=utf-8;' })
    
    const url = window.URL.createObjectURL(workbook)
    const link = document.createElement('a')
    link.href = url
    link.download = `支出管理数据_${new Date().toISOString().slice(0, 10)}.csv`
    link.click()
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
    
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败：' + error.message)
  }
}

const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

const handleSizeChange = (size) => {
  pagination.size = size
  loadData()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadData()
}

const handleSubmit = async () => {
  try {
    // 表单验证
    await formRef.value.validate()
    
    if (dialogType.value === 'add') {
      await addExpenseBill(form)
    } else {
      await updateExpenseBill(form)
    }
    ElMessage.success(dialogType.value === 'add' ? '新增成功' : '编辑成功')
    dialogVisible.value = false
    loadData()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  }
}

const resetForm = () => {
  Object.assign(form, {
    id: null,
    billNo: '',
    itemId: '',
    amount: 0,
    billDate: '',
    status: 1,
    remark: ''
  })
}

// 自动生成单据编号
const generateBillNo = async () => {
  try {
    // 获取当前日期
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const dateStr = `${year}${month}${day}`

    // 获取今天的单据数量作为序号
    const today = `${year}-${month}-${day}`
    const params = {
      pageNum: 1,
      pageSize: 1000,
      startDate: today,
      endDate: today
    }

    const page = await getExpenseBillList(params)
    const todayRecords = page?.records || []
    const todayCount = todayRecords.length + 1
    const sequence = String(todayCount).padStart(3, '0')

    // 生成单据编号：ZC + 年月日 + 3位序号
    const billNo = `ZC${dateStr}${sequence}`
    form.billNo = billNo
    ElMessage.success('单据编号生成成功')
  } catch (error) {
    console.error('生成单据编号失败:', error)
    // 如果出错，使用时间戳作为序号
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const dateStr = `${year}${month}${day}`
    const timestamp = Date.now().toString().slice(-3)
    const billNo = `ZC${dateStr}${timestamp}`
    form.billNo = billNo
    ElMessage.success('单据编号生成成功')
  }
}

const loadData = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.size,
      ...searchForm
    }
    
    // 如果有日期范围，添加到参数中
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startDate = searchForm.dateRange[0]
      params.endDate = searchForm.dateRange[1]
    }
    
    // 调用API获取数据
    const response = await getExpenseBillList(params)
    
    // 检查响应格式
    if (response && response.code === 200 && response.data) {
      // 标准Result格式
      const page = response.data
      tableData.value = page?.records || []
      pagination.total = page?.total || 0
    } else if (response && response.records) {
      // 直接Page格式
      tableData.value = response.records || []
      pagination.total = response.total || 0
    } else {
      console.error('API返回错误:', response)
      ElMessage.error('获取数据失败：数据格式不正确')
      tableData.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

const loadStats = async () => {
  try {
    const response = await getExpenseBillStats()
    
    // 检查响应格式
    if (response && response.code === 200 && response.data) {
      // 标准Result格式
      const stats = response.data
      totalExpense.value = parseFloat(stats?.totalAmount || 0)
      totalCount.value = parseInt(stats?.totalCount || 0)
    } else if (response && response.totalAmount !== undefined) {
      // 直接数据格式
      totalExpense.value = parseFloat(response.totalAmount || 0)
      totalCount.value = parseInt(response.totalCount || 0)
    } else {
      console.error('统计数据响应格式错误:', response)
      totalExpense.value = 0
      totalCount.value = 0
    }
    
    // 暂时设置默认值，后续可扩展
    monthlyExpense.value = 0
    pendingCount.value = 0
    approvedCount.value = 0
  } catch (error) {
    console.error('加载统计数据失败:', error)
    totalExpense.value = 0
    totalCount.value = 0
    monthlyExpense.value = 0
    pendingCount.value = 0
    approvedCount.value = 0
  }
}

// 工具方法
// 日期格式化：YYYY-MM-DD
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  if (isNaN(d)) return String(date).slice(0, 10)
  const y = d.getFullYear()
  const m = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  return `${y}-${m}-${day}`
}
const getExpenseTypeText = (type) => {
  const typeMap = {
    purchase: '采购支出',
    labor: '人工支出',
    operation: '运营支出',
    other: '其他支出'
  }
  return typeMap[type] || type
}

const getExpenseTypeTag = (type) => {
  const tagMap = {
    purchase: 'danger',
    labor: 'warning',
    operation: 'info',
    other: 'success'
  }
  return tagMap[type] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    1: '待审核',
    2: '已审核',
    3: '已拒绝'
  }
  return statusMap[status] || status
}

const getStatusType = (status) => {
  const typeMap = {
    1: 'warning',
    2: 'success',
    3: 'danger'
  }
  return typeMap[status] || 'info'
}

// 生命周期
onMounted(() => {
  loadData()
  loadStats()
})
</script>

<style scoped>
.expense-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.stats-card {
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
  padding: 20px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #f56c6c;
}

.stat-label {
  margin-top: 8px;
  color: #666;
}

.action-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.amount {
  color: #f56c6c;
  font-weight: bold;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
}
</style>